//--------------------------------------------------------------------------------------------------------------
// <copyright file="RowConvert.cs" company="Microsoft Corporation" author="David Martos" date="01/02/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using CSP.Core;
using CSP.MembershipInterface.ObjectModel;
using System.Collections.Generic;
using System.Collections;
using System.Xml;

namespace CSP.CRM.Integration
{

    /// <summary>
    /// This class converts CRM entities to raw .NET DataSets. 
    /// </summary>
    public class RowConvert
    {

        //#region Exception handling
     
        //public RowConvert()
        //{
        //    Errors.InitializeLog();
        //}
        //#endregion

        //#region Case Statuses

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="caseStatus"></param>
        ///// <returns></returns>
        //public CSPLib.CrmSdk.IncidentStateInfo GetCrmStatusByCaseStatus(CaseStatus caseStatus)
        //{
        //    IncidentStateInfo stateInfo = new IncidentStateInfo();
        //    switch (caseStatus)
        //    {
        //        case CaseStatus.Approved: stateInfo.Value = IncidentState.Resolved; break;
        //        case CaseStatus.Denied: stateInfo.Value = IncidentState.Canceled; break;
        //        case CaseStatus.Submitted: stateInfo.Value = IncidentState.Active; break;
        //        case CaseStatus.Pending: stateInfo.Value = IncidentState.Active; break;
        //        default: stateInfo.Value = IncidentState.Active; break;
        //    }
        //    return stateInfo;
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="caseStatus"></param>
        ///// <returns></returns>
        //public static CaseStatus GetCaseStatusByCrmStatus(CSPLib.CrmSdk.Status caseStatus)
        //{
        //  //CaseStatus.Approved, CaseStatus.Denied, CaseStatus.Pending, CaseStatus.Submitted
        //    // Uses Status reason in CRM = statuscode attribute
        //    // State, Status
        //    // 0, 1      -> Active, Submitted           CaseStatus.Submitted
        //    // 0, 200002 -> Active, Procedure finished  CaseStatus.Submitted
        //    // 1, 5      -> Resolved, Case closed       CaseStatus.Approved?
        //    // 1, 200000 -> Resolved, Approved          CaseStatus.Approved
        //    // 1, 200001 -> Resolved, Denied            CaseStatus.Denied
        //    // 2, 6      -> Canceled, Canceled          CaseStatus.Denied
        //    switch (caseStatus.Value)
        //    {
        //        case 1: return CaseStatus.Pending;
        //        case 5: case 200000: return CaseStatus.Approved;
        //        case 6: case 200001: return CaseStatus.Denied;
        //        default: return CaseStatus.Pending;
        //    }
        //}

        //#endregion

        //#region Case Types
        ///// <summary>
        ///// Hashtable which contains all the different case types to deal with.
        ///// </summary>
        //private static Hashtable _caseTypes;
        ///// <summary>
        ///// Hashtable which contains all the different case types to deal with.
        ///// </summary>
        //private static Hashtable _crmCaseTypes;
        ///// <summary>
        ///// 
        ///// </summary>
        //protected static Hashtable CaseTypes
        //{
        //    get
        //    {
        //        if (_caseTypes == null || _crmCaseTypes == null)
        //        {
        //            string configurationPath = System.Configuration.ConfigurationManager.AppSettings["csp_configurationpath"];

        //            _caseTypes = new Hashtable();
        //            _crmCaseTypes = new Hashtable();
        //            XmlDocument caseTypesXml = new XmlDocument();
        //            caseTypesXml.Load(configurationPath);
        //            XmlNode caseTypesNode = caseTypesXml.SelectSingleNode("//caseTypes");
        //            foreach (XmlNode node in caseTypesNode.ChildNodes)
        //            {
        //                _caseTypes.Add(Convert.ToInt32(node.Attributes["id"].Value), Convert.ToInt32(node.InnerText));
        //                _crmCaseTypes.Add(Convert.ToInt32(node.InnerText), Convert.ToInt32(node.Attributes["id"].Value));
        //            }

        //        }
        //        return _caseTypes;
        //    }
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        //protected static Hashtable CrmCaseTypes
        //{
        //    get
        //    {
        //        if (_caseTypes == null || _crmCaseTypes == null)
        //        {
        //            string configurationPath = System.Configuration.ConfigurationManager.AppSettings["csp_configurationpath"];

        //            _caseTypes = new Hashtable();
        //            _crmCaseTypes = new Hashtable();
        //            XmlDocument caseTypesXml = new XmlDocument();
        //            caseTypesXml.Load(configurationPath);
        //            XmlNode caseTypesNode = caseTypesXml.SelectSingleNode("//caseTypes");
        //            foreach (XmlNode node in caseTypesNode.ChildNodes)
        //            {
        //                _caseTypes.Add(Convert.ToInt32(node.Attributes["id"].Value), Convert.ToInt32(node.InnerText));
        //                _crmCaseTypes.Add(Convert.ToInt32(node.InnerText), (CaseType)Convert.ToInt32(node.Attributes["id"].Value));
        //            }

        //        }
        //        return _crmCaseTypes;
        //    }
        //}

        ///// <summary>
        ///// Gets the CRM case type corresponding to the CMS case type
        ///// </summary>
        ///// <param name="id">CMS case type</param>
        ///// <returns>CRM case type</returns>
        //public static int GetCrmCaseTypeById(CaseType type)
        //{
        //    if (CaseTypes.ContainsKey((int)type))
        //        return Convert.ToInt32(CaseTypes[(int)type]);
        //    return -1;
        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="crmtype"></param>
        ///// <returns></returns>
        //public static CaseType GetCaseTypeByCrmId(int crmtype)
        //{
        //    if (CrmCaseTypes.ContainsKey(crmtype))
        //        return (CaseType)CrmCaseTypes[crmtype];
        //    throw new LrgException();
        //}

        //#endregion

        ///// <summary>
        ///// Converts a CRM BusinessEntityCollection of incidents to an array of CSP Case entities
        ///// </summary>
        ///// <param name="collection">CRM BusinessEntityCollection of incidents</param>
        ///// <returns>Arran of CSP Case entities</returns>
        //public static Case[] IncidentCollectionToCaseArray(BusinessEntityCollection collection)
        //{

        //    List<Case> cases = new List<Case>();

        //    // TODO: Follow up date
        //    try
        //    {
        //        foreach (BusinessEntity entity in collection.BusinessEntities)
        //        {
        //            incident _incident = (incident)entity;
        //            try
        //            {
        //                Case _case = ParseIncident(_incident);
        //                cases.Add(_case);
        //            }
        //            catch
        //            { 
        //                // TODO: just for testing purposes, as some of the entities could be wrongly created
        //            }
        //        }
        //        return cases.ToArray();
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.IncidentCollectionToDataSetError), ex);
        //        throw new LrgException(ex.Message, ex);
        //    }
        //}

        //public static Case ParseIncident(incident _incident)
        //{
        //    Case _case = new Case();

        //    _case.ID = _incident.incidentid.Value.ToString();
        //    _case.Type = GetCaseTypeByCrmId(_incident.csp_proceduretype.Value); // CaseType.BuildingPermit; // _incident.casetypecode == null ? CaseType.BuildingPermit : (CaseType)_incident.casetypecode.Value;
        //    _case.Title = _incident.ticketnumber;
        //    _case.Description = _incident.csp_proceduretype.name;
        //    _case.Status = GetCaseStatusByCrmStatus(_incident.statuscode); // CaseStatus.Pending; // GetCaseTypeByCrmId((int)_incident.statecode.Value); // CaseStatus.Pending; // (CaseStatus)_incident.statecode.Value;
        //    _case.DueDate = Convert.ToDateTime(_incident.createdon.Value);


        //    _case.RoleType = CaseRoleType.CivilServant;

        //    return _case;
        //}

        //#region public static Case IncidentToCase(incident _incident, contact _contact)

        ///// <summary>
        ///// Converts an incident CRM business entity to a CSP Case entity
        ///// </summary>
        ///// <param name="_incident">CRM incident business entity</param>
        ///// <param name="_contact">CRM contact business entity</param>
        ///// <returns></returns>
        //public static Case IncidentToCase(incident _incident, contact _contact)
        //{
        //    Case _case = ParseIncident(_incident);

        //    _case.RequestorID = _contact.csp_username;
        //    _case.RequestorName = _contact.fullname;
        //    _case.RequestorEmail = _contact.emailaddress1;
        //    _case.RequestorAddress = _contact.address1_line1;
        //    _case.RequestorCity = _contact.address1_city;
        //    _case.RequestorPostalCode = _contact.address1_postalcode;
        //    _case.RequestorPhone = _contact.address1_telephone1;
        //    _case.FormXml = string.Empty;
        //    _case.ExternalDocumentRef = string.Empty;
        //    _case.OwnerID = string.Empty;
        //    _case.LastModified = DateTime.Now;
        //    _case.CreatedDate = DateTime.Now;

        //    return _case;
        //}

        //#endregion

        //#region public static DataSet CrmStatusCollectionToMossStatusCollection(DataTable CrmStatusCollection, int caseTypeId)
        ///// <summary>
        ///// Converts a CRM contact BusinessEntityCollection of contacts to a raw .NET dataset 
        ///// </summary>
        ///// <param name="collection">CRM BusinessEntityCollection of contacts</param>
        ///// <returns>Raw .NET dataset</returns>
        //public static DataSet ContactCollectionToDataset(BusinessEntityCollection collection)
        //{
        //    try
        //    {
        //        DataSet ds = new DataSet();

        //        ds.Tables.Add("Citizen");
        //        ds.Tables[0].Columns.Add("Username", typeof(string));
        //        ds.Tables[0].Columns.Add("FirstName", typeof(string));
        //        ds.Tables[0].Columns.Add("LastName", typeof(string));
        //        ds.Tables[0].Columns.Add("DisplayName", typeof(string));
        //        ds.Tables[0].Columns.Add("EmailAddress", typeof(string));
        //        ds.Tables[0].Columns.Add("DefaultGroup", typeof(string));
        //        ds.Tables[0].Columns.Add("Address", typeof(string));
        //        ds.Tables[0].Columns.Add("City", typeof(string));
        //        ds.Tables[0].Columns.Add("PostalCode", typeof(string));
        //        ds.Tables[0].Columns.Add("Phone", typeof(string));
        //        ds.Tables[0].Columns.Add("Children", typeof(string));
        //        ds.Tables[0].Columns.Add("ElderlyRelatives", typeof(string));
        //        ds.Tables[0].Columns.Add("PhotoUrl", typeof(string));
        //        ds.Tables[0].Columns.Add("LastModified", typeof(DateTime));
        //        ds.Tables[0].Columns.Add("CreatedDate", typeof(DateTime));


        //        foreach (BusinessEntity entity in collection.BusinessEntities)
        //        {
        //            contact _contact = (contact)entity;

        //            ds.Tables["Citizen"].Rows.Add(new object[] {
        //    _contact.csp_username,
        //    _contact.firstname,
        //    _contact.lastname,
        //    _contact.fullname,
        //    _contact.emailaddress1,
        //    "",
        //    _contact.address1_line1,
        //    _contact.address1_city,
        //    _contact.address1_postalcode,
        //    _contact.address1_telephone1,
        //    _contact.numberofchildren,
        //    "",
        //    "http://www.lrgserver.local/MyCity/Authenticated/Citizen%20Photos/_t/marc_bmp.jpg",
        //    DateTime.Now,
        //    DateTime.Now
        //  });
        //        }

        //        ds.AcceptChanges();

        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.ContactCollectionToDataSetError), ex);
        //        throw new LrgException();
        //    }

        //}
        //#endregion


        //public static CitizenRequest[] ContactCollectionToCitizenRequests(BusinessEntityCollection collection)
        //{

        //    List<CitizenRequest> requests = new List<CitizenRequest>();

        //    try
        //    {
        //        foreach (BusinessEntity entity in collection.BusinessEntities)
        //        {
        //            contact _contact = (contact)entity;
        //            try
        //            {
        //                CitizenRequest _request = new CitizenRequest();
        //                //                        _request.RequestType = new CitizenRequestType();
        //                _request.RequestType = CitizenRequestType.Add;



        //                _request.EmailAddress = _contact.emailaddress1;
        //                _request.Address = _contact.address1_line1;
        //                _request.City = _contact.address1_city;
        //                //_contact.createdon.Value = DateTime.Now.ToShortDateString();
        //                //_contact.modifiedon.Value = DateTime.Now.ToShortDateString();
        //                _request.DisplayName = _contact.fullname;
        //                _request.FirstName = _contact.firstname;
        //                _request.LastName = _contact.lastname;
        //                _request.PostalCode = _contact.address1_postalcode;
        //                _request.Phone = _contact.address1_telephone1;
        //                _request.PhotoUrl = _contact.csp_picture;
        //                _request.Username = _contact.csp_username;
        //                _request.Password = _contact.csp_password;
        //                //_contact.csp_enabled.Value = false;


        //                requests.Add(_request);
        //            }
        //            catch (Exception ex)
        //            { }
        //        }
        //        return requests.ToArray();
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.IncidentCollectionToDataSetError), ex);
        //        throw new LrgException();
        //    }

        //}

        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="collection"></param>
        ///// <returns></returns>
        //public static Citizen[] ContactCollectionToCitizenArray(BusinessEntityCollection collection)
        //{

        //    List<Citizen> citizens = new List<Citizen>();

        //    try
        //    {
        //        foreach (BusinessEntity entity in collection.BusinessEntities)
        //        {
        //            contact _contact = (contact)entity;
        //            try
        //            {
        //                Citizen _citizen = ContactToCitizen(_contact);
        //                citizens.Add(_citizen);
        //            }
        //            catch (Exception ex)
        //            { }
        //        }
        //        return citizens.ToArray();
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.IncidentCollectionToDataSetError), ex);
        //        throw new LrgException();
        //    }

        //}

        //public static CitizenRequest ContactCollectionToCitizenRequest(BusinessEntityCollection collection)
        //{

        //    try
        //    {
        //        foreach (BusinessEntity entity in collection.BusinessEntities)
        //        {
        //            contact _contact = (contact)entity;
        //            CitizenRequest _request = new CitizenRequest();
        //            //                        _request.RequestType = new CitizenRequestType();
        //            _request.RequestType = CitizenRequestType.Add;
        //            _request.DefaultGroup = "Viewers";



        //            _request.EmailAddress = _contact.emailaddress1;
        //            _request.Address = _contact.address1_line1;
        //            _request.City = _contact.address1_city;
        //            //_contact.createdon.Value = DateTime.Now.ToShortDateString();
        //            //_contact.modifiedon.Value = DateTime.Now.ToShortDateString();
        //            _request.DisplayName = _contact.fullname;
        //            _request.FirstName = _contact.firstname;
        //            _request.LastName = _contact.lastname;
        //            _request.PostalCode = _contact.address1_postalcode;
        //            _request.Phone = _contact.address1_telephone1;
        //            _request.PhotoUrl = _contact.csp_picture;
        //            _request.Username = _contact.csp_username;
        //            _request.Password = _contact.csp_password;
        //            //_contact.csp_enabled.Value = false;


        //            return _request;
        //        }
        //        throw new LrgException();
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.IncidentCollectionToDataSetError), ex);
        //        throw new LrgException();
        //    }

        //}


        ////#region public static DataSet ContactToDataset(contact _contact)
        /////// <summary>
        /////// Converts a CRM contact to a raw .NET dataset
        /////// </summary>
        /////// <param name="_contact">CRM contact</param>
        /////// <returns>Raw .NET dataset</returns>
        ////public static DataSet ContactToDataset(contact _contact)
        ////{
        ////    try
        ////    {
        ////        DataSet ds = new DataSet();

        ////        ds.Tables.Add("Citizen");
        ////        ds.Tables[0].Columns.Add("Username", typeof(string));
        ////        ds.Tables[0].Columns.Add("FirstName", typeof(string));
        ////        ds.Tables[0].Columns.Add("LastName", typeof(string));
        ////        ds.Tables[0].Columns.Add("DisplayName", typeof(string));
        ////        ds.Tables[0].Columns.Add("EmailAddress", typeof(string));
        ////        ds.Tables[0].Columns.Add("DefaultGroup", typeof(string));
        ////        ds.Tables[0].Columns.Add("Address", typeof(string));
        ////        ds.Tables[0].Columns.Add("City", typeof(string));
        ////        ds.Tables[0].Columns.Add("PostalCode", typeof(string));
        ////        ds.Tables[0].Columns.Add("Phone", typeof(string));
        ////        ds.Tables[0].Columns.Add("Children", typeof(string));
        ////        ds.Tables[0].Columns.Add("ElderlyRelatives", typeof(string));
        ////        ds.Tables[0].Columns.Add("PhotoUrl", typeof(string));
        ////        ds.Tables[0].Columns.Add("LastModified", typeof(DateTime));
        ////        ds.Tables[0].Columns.Add("CreatedDate", typeof(DateTime));

        ////        ds.Tables[0].Rows.Add(new object[] {
        ////_contact.csp_username,
        ////_contact.firstname,
        ////_contact.lastname,
        ////_contact.fullname,
        ////_contact.emailaddress1,
        ////"",
        ////_contact.address1_line1,
        ////_contact.address1_city,
        ////_contact.address1_postalcode,
        ////_contact.address1_telephone1,
        ////_contact.numberofchildren,
        ////"",
        ////"http://www.lrgserver.local/MyCity/Authenticated/Citizen%20Photos/_t/marc_bmp.jpg",
        ////DateTime.Now,
        ////DateTime.Now});

        ////        ds.AcceptChanges();
        ////        return ds;

        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        log.Error(new LogMessage(LogMessageType.ContactToDataSetError), ex);
        ////        throw new LrgException();
        ////    }
        ////}
        ////#endregion

        //#region public static Citizen ContactToCitizen(contact _contact)
        ///// <summary>
        ///// Converts a CRM contact into a CSP Citizen
        ///// </summary>
        ///// <param name="_contact">CRM contact entity</param>
        ///// <returns>CSP Citizen</returns>
        //public static Citizen ContactToCitizen(contact _contact)
        //{
        //    try
        //    {
        //        Citizen citizen = new Citizen();
        //        citizen.Username = _contact.csp_username;
        //        citizen.FirstName = _contact.firstname;
        //        citizen.LastName = _contact.lastname;
        //        citizen.DisplayName = _contact.fullname;
        //        citizen.EmailAddress = _contact.emailaddress1;
        //        citizen.DefaultGroup = "Viewers";
        //        citizen.Address = _contact.address1_line1;
        //        citizen.City = _contact.address1_city;
        //        citizen.PostalCode = _contact.address1_postalcode;
        //        citizen.Phone = _contact.address1_telephone1;
        //        citizen.Children = _contact.csp_children.Value.ToString();
        //        citizen.ElderlyRelatives = _contact.csp_elderlyrelatives.Value.ToString();
        //        citizen.PhotoUrl = _contact.csp_picture;
        //        //citizen.LastModified = Convert.ToDateTime(_contact.modifiedon.Value);
        //        //citizen.CreatedDate = Convert.ToDateTime(_contact.createdon.Value);

        //        return citizen;

        //    }
        //    catch (Exception ex)
        //    {
        //        log.Error(new LogMessage(LogMessageType.ContactToDataSetError), ex);
        //        throw new LrgException();
        //    }
        //}
        //#endregion
    }
}